package com.itheima.nio.tomcat.entry;

import com.itheima.nio.tomcat.domain.HttpRequest;
import com.itheima.nio.tomcat.domain.HttpResponse;
import com.itheima.nio.tomcat.handler.AcceptHandler;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class HttpServer {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(80));
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true){
            int select = selector.select();
            if (select != 0){
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()){
                        AcceptHandler acceptHandler = new AcceptHandler();
                        SocketChannel socketChannel = acceptHandler.connectSocketChannel(selectionKey);
                    } else if (selectionKey.isReadable()){
                        HttpRequest httpRequest = new HttpRequest(selectionKey);
                        httpRequest.parse();
                        System.out.println("请求数据解析完毕");
                        HttpResponse httpResponse = new HttpResponse(selectionKey);
                        httpResponse.setHttpRequest(httpRequest);
                        httpResponse.sendStaticResource();
                    }
                    iterator.remove();
                }
            }
        }
    }
}
